-- UIDungeonTopMenu
-- create by zouyb
-- 地牢中顶部菜单

-- UIDungeonTopMenu
UIDungeonTopMenu = class("UIDungeonTopMenu", function()
    return {};
end);

function UIDungeonTopMenu.create(node)
    return UIDungeonTopMenu.new(node);
end

-- 是否在自动战斗中
local inFight = false;

-- 构造函数
function UIDungeonTopMenu:ctor(node)
    self.node = node;
    local scaleFix = 1;

    -- 修正的半角字符数 必须是 3 的整倍数，否则汉字会出问题
    local fixLenZh = 12;
    local fixLenEn = 8;

    -- 地牢名称
    local name = DungeonAreaM.query(DungeonM.getDungeonId(), "name");
    local newName = name;
    self.nameLabel = findChildByName(self.node, "name");
    local kerning = -2;
    if not isFullWidthLang() then
        kerning = 0;
    end

    -- 同步下数量
    self:syncBallCount();

    -- 需要针对过长名称做修正
    local strLen = string.len(name);
    if getLang() == "th" then
        newName = name;
    elseif isFullWidthLang() then
        if strLen > fixLenZh then
            local spacePos = string.find(name, " ");

            if spacePos ~= nil and spacePos - 1 < fixLenZh then
                fixLenZh = spacePos - 1;
            end

            newName = string.sub(name, 1, fixLenZh) .. "...";
        end
    else
        if strLen > fixLenEn then
            local spacePos = string.find(name, " ");

            if spacePos ~= nil and spacePos - 1 < fixLenEn then
                fixLenEn = spacePos - 1;
            end
            newName = string.sub(name, 1, fixLenEn) .. "...";
        end
    end

    -- 地牢层数
    local layer = DungeonM.currentLayer();

    -- 拼接楼层信息
    local titleText = string.format("%s %dF", newName, layer);

    TextStyleM.setTextStyle(self.nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, nil, nil, 1);
    self.nameLabel:setString(titleText);

    -- 探索点
    self.spLabel = findChildByName(self.node, "sp_val");
    TextStyleM.setTextStyle(self.spLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_WHITE, true, nil, nil, 1);
    self.spLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
    self.spLabel:setScaleX(1.2);

    -- 显示迷宫出口动画
    local exitNode = findChildByName(self.node, "building");
    playEffect(exitNode, 1102, -4, -3);

    -- 显示自动战斗按钮
    self:showAutoBtn();

    self:registerTouchEvent();

    self:updateUI();

end

-- 更新UI
function UIDungeonTopMenu:updateUI(showValue)
    for i = 1, DragonWishM.getWishNeedCount() do
        local img = findChildByName(self.node, "zhu" .. i);
        if img then
            img:setVisible(false);
        end
    end

    local sp = ME.user:getSp();
    local reduceSp = ME.user.dbase:queryTemp("reduceSp", 0)
    local amount = sp - reduceSp;
    local spAmont = math.max(0, amount);

    local spValue = showValue and showValue or spAmont;

    self.spLabel:setString(tostring(spValue));

    local amount = self:getCurUIBallCount();
    for i = 1, DragonWishM.getWishNeedCount() do
        local img = findChildByName(self.node, "zhu" .. i);
        if not img then
            return;
        end
        if amount >= i then
            img:setVisible(true);
        else
            img:setVisible(false);
        end
    end
end

-- 注册点击事件
function UIDungeonTopMenu:registerTouchEvent()
     -- 区域信息按钮
    local buildingBtn = findChildByName(self.node, "building/exit_door");
    local function onBuildingClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 统计窗口在，表示刚退出地牢，无需处理
            if UIMgr.getCurrentScene():isOpen("UICombatStat") then
                return;
            end

            if UIMgr.getCurrentScene():isOpen("UIDungeonInfo") then
                UIMgr.getCurrentScene():removeFormByName("UIDungeonInfo");
            end

            local uiInfo = UIDungeonInfo.create();
            UIMgr.getCurrentScene():addForm(uiInfo);
            AudioM.playFx("ui_open1");
        end
    end
    buildingBtn:addTouchEventListener(onBuildingClick);

    -- 扩大按钮响应区域
    local btnBuildingPanel = findChildByName(self.node, "building_panel");
    btnBuildingPanel:setTouchEnabled(true);
    btnBuildingPanel:addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 统计窗口在，表示刚退出地牢，无需处理
            if UIMgr.getCurrentScene():isOpen("UICombatStat") then
                return;
            end

            if UIMgr.getCurrentScene():isOpen("UIDungeonInfo") then
                UIMgr.getCurrentScene():removeFormByName("UIDungeonInfo");
            end

            local uiInfo = UIDungeonInfo.create();
            UIMgr.getCurrentScene():addForm(uiInfo);
            AudioM.playFx("ui_open1");
        end
    end);

    -- 设置
    local settingBtn = findChildByName(self.node, "setting");
    local function onSettingClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- TODO 暂时让玩家查看错误信息页面
            AudioM.playFx("button_set");
            if UIMgr.getCurrentScene():isOpen("UISystemSetting") then
                UIMgr.getCurrentScene():removeFormByName("UISystemSetting");
            end

            local uiSetting = UISystemSetting.create();
            UIMgr:getCurrentScene():addForm(uiSetting);

            if DEBUG_MODE == 1 or RELEASE_LOG_ENABLED == 1 then
                print(cc.Director:getInstance():getTextureCache():getCachedTextureInfo());

                printLuaMemSize("before GC");
                enableGC();
                printLuaMemSize("after GC");
                disableGC();

                printEffectStat();
            end
        end
    end
    settingBtn:addTouchEventListener(onSettingClick);

    -- 扩大按钮响应区域
    local btnSysSetPanel = findChildByName(self.node, "setting_panel");
    btnSysSetPanel:setTouchEnabled(true);
    btnSysSetPanel:addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            if UIMgr.getCurrentScene():isOpen("UISystemSetting") then
                UIMgr.getCurrentScene():removeFormByName("UISystemSetting");
            end

            local uiSetting = UISystemSetting.create();
            UIMgr:getCurrentScene():addForm(uiSetting);
        end
    end);

    -- 注册事件
    EventMgr.removeAll("UIDungeonTopMenu");
    EventMgr.register("UIDungeonTopMenu", event.START_AUTO_FIGHT, function(para)
        local uiDungeonMain = UIMgr.getCurrentScene():getFormByName("UIDungeonMain");
        if not uiDungeonMain then
            return;
        end
        self:setText();
    end);
    EventMgr.register("UIDungeonTopMenu", event.STOP_AUTO_FIGHT, function(para)
        local uiDungeonMain = UIMgr.getCurrentScene():getFormByName("UIDungeonMain");
        if not uiDungeonMain then
            return;
        end
        self:setText();
    end);
end

-- 自动战斗按钮
function UIDungeonTopMenu:setText()
    local autoBtn = findChildByName(self.node, "atuo_fight_btn");

    TextStyleM.setTextStyle(autoBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, nil, nil, nil, nil, nil, true);
    if AutoFightM.inFighting() then
        autoBtn:setTitleText(getLocStr("stop_auto_fight"));
    else
        autoBtn:setTitleText(getLocStr("start_auto_fight"));
    end
end

function UIDungeonTopMenu:setNotInFight()
    inFight = false;
    self:showAutoBtn();
end

function UIDungeonTopMenu:continue()
    self:setText();
end

function UIDungeonTopMenu:showAutoBtn()
    local isShow = false;

    if DEBUG_AUTO == 1 or AutoFightM.canAutoFight() then
        -- debug开关已开启或者已经开启自动战斗功能
        isShow = true;
    end

    local autoBtn = findChildByName(self.node, "atuo_fight_btn");

    if not isShow then
        autoBtn:setVisible(false);
        return;
    end

    autoBtn:setVisible(true);
    self:setText();

    if not autoBtn.hasHandler then
        local function onClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                if not DungeonM.isInDungeon() then
                    return false;
                end
                AutoFightM.switch();

                self:setText();
            end
        end
        autoBtn:addTouchEventListener(onClick);
        autoBtn.hasHandler = true;
    end
end

-- 设置可见性
function UIDungeonTopMenu:setVisible(flag)
    self.node:setVisible(flag);
end

-- 获取探索点图标组件
function UIDungeonTopMenu:getSpIconNode()
    return findChildByName(self.node, "sp_bg");
end

-- 获取探索点文本组件
function UIDungeonTopMenu:getSpTextNode()
    return findChildByName(self.node, "sp_val");
end

-- 获取下一个待开启龙珠图标组件
function UIDungeonTopMenu:getDragonBallNode()
   -- local nextPos = DragonWishM.getWishItemCount();
    local nextPos = self:getCurUIBallCount() + 1;
    local img = findChildByName(self.node, "zhu" .. nextPos);
    return img;
end

-- 获取龙珠盘底图组件
function UIDungeonTopMenu:getDragonBallBgNode()
    local bg = findChildByName(self.node, "zhu_bg");
    return bg;
end

-- 获取龙珠盘底图后面组件
function UIDungeonTopMenu:getDragonBallBgBackNode()
    local bgBack = findChildByName(self.node, "zhu_bg_back");
    return bgBack;
end

-- 获取当前表现层的龙珠数量
function UIDungeonTopMenu:getCurUIBallCount()
    return self.curUIBallCount;
end

-- 设置当前表现层的龙珠数量
function UIDungeonTopMenu:setCurUIBallCount(num)
    self.curUIBallCount = num;
end

-- 同步下逻辑和表现层的数量
function UIDungeonTopMenu:syncBallCount()
    self.curUIBallCount = DragonWishM.getWishItemCount();
end
